package com.acminds.fotoporter.ui.servlets;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.acminds.fotoporter.persistence.dto.Image;
import com.acminds.fotoporter.ui.ImageHolder;
import com.acminds.fotoporter.ui.controllers.OrderAction;
import com.acminds.fotoporter.utils.Utils;

/**
 * 
 * @author MANSUR
 *
 */
public class ImageServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/*
	 * mime types:
	 * image/bmp
	 * image/gif
	 * image/jpeg
	 * image/png
	 * 
	 * image/tiff
	 * image/svg
	 */
	private Log logger = LogFactory.getLog(ImageServlet.class);
	
	
	public void init() throws ServletException {
		super.init();
		logger.info("Image rendering servlet initialized");
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		try {
			String rowNum = request.getParameter("rowNum");
			ImageHolder aa = getImageHolder(request, request.getParameter("imgHolder"));
			if(Utils.isEmpty(aa.getImages()))
				return;
			Image image = aa.getImages().get(Integer.valueOf(rowNum));
			if(image == null)
			{
				response.getWriter().print("No image [" + rowNum + 
						"] found");
				response.setContentType("text/plain");
				return;
			}
			response.setContentType(image.getMimeType());
			OutputStream out = response.getOutputStream();
			out.write(image.getPreviewData());
		} catch (NumberFormatException e) {
			logger.error(e.getMessage(), e);
			throw new ServletException(e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new ServletException(e);
		}
	}
	
	private OrderAction getImageHolder(HttpServletRequest request, String beanName){
		Object obj = request.getAttribute(beanName);
		if(obj == null)
			obj = request.getSession().getAttribute(beanName);
		return (OrderAction)obj;
	}

	
	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) 
		throws ServletException, IOException 
	{
		doGet(arg0, arg1);
	}
}
